<template>
  <div class="scenic-management">
    <!-- 页面标题和统计信息 -->
    <div class="header">
      <h2 class="header-title">景区管理</h2>
      <div class="header-stats">
        <div class="stat-item">
          <span class="stat-value">{{ totalScenics }}</span>
          <span>景区总数</span>
        </div>
        <div class="stat-item">
          <span class="stat-value">{{ activeScenics }}</span>
          <span>开放中</span>
        </div>
        <div class="stat-item">
          <span class="stat-value">{{ selectedScenics.length }}</span>
          <span>已选择</span>
        </div>
      </div>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-container">
      <el-form :model="filterForm" class="filter-form">
        <el-form-item label="搜索" class="filter-item">
          <el-input
            v-model="searchQuery"
            placeholder="请输入景区名称"
            style="width: 240px"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button :icon="Search" @click="handleSearch" />
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="状态" class="filter-item">
          <el-select v-model="filterForm.status" placeholder="请选择状态" @change="handleFilter">
            <el-option label="全部" value="" />
            <el-option label="开放" :value="SCENIC_STATUS.ACTIVE" />
            <el-option label="关闭" :value="SCENIC_STATUS.INACTIVE" />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="分类" class="filter-item">
          <el-select v-model="filterForm.category" placeholder="请选择分类" @change="handleFilter">
            <el-option label="全部" value="" />
            <el-option
              v-for="item in categories"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->

        

        <el-form-item class="filter-item">
          <el-button @click="handleResetFilter">重置</el-button>
          <el-button type="primary" @click="handleRefresh" :icon="Refresh">刷新</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <div>
        <el-button type="primary" @click="handleAddScenic" :icon="Plus">添加景区</el-button>
        <!-- <el-button
          type="danger"
          :disabled="selectedScenics.length === 0"
          @click="handleBatchDelete"
          :icon="Delete"
        >
          批量删除
        </el-button> -->
      </div>
    </div>

    <!-- 景区列表表格 -->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="scenicList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="景区名称" prop="name" width="200" fixed="left">
          <template #default="{ row }">
            <div class="scenic-name">{{ row.name }}</div>
          </template>
        </el-table-column>
        
        <!-- <el-table-column label="景区地址" width="200">
          <template #default="{ row }">
            <div class="scenic-address">
              <el-icon class="address-icon"><Location /></el-icon>
              {{ row.address }}
            </div>
          </template>
        </el-table-column> -->

        <!-- <el-table-column label="分类" width="120">
          <template #default="{ row }">
            {{ getCategoryName(row.category) }}
          </template>
        </el-table-column> -->

        <el-table-column label="门票价格" width="100">
          <template #default="{ row }">
            {{ row.ticketPrice === 0 ? '免费' : `¥${row.ticketPrice}` }}
          </template>
        </el-table-column>

        <el-table-column label="景点描述" width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="description-text">
              {{ row.description || '-' }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="预约须知" width="180" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="notice-text">
              {{ row.bookingNotice || row.reservationNotice || '-' }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="退款说明" width="180" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="policy-text">
              {{ row.refundPolicy || '-' }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="使用说明" width="180" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="guide-text">
              {{ row.usageGuide || row.usageInstructions || '-' }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="库存" width="80">
          <template #default="{ row }">
            <span :class="{ 'low-stock': row.stock < 50 }">{{ row.stock }}张</span>
          </template>
        </el-table-column>

        <el-table-column label="提前预约" width="100">
          <template #default="{ row }">
            {{ row.advanceDays }}天
          </template>
        </el-table-column>

        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="SCENIC_STATUS.ACTIVE"
              :inactive-value="SCENIC_STATUS.INACTIVE"
              @change="(val) => handleStatusChange(row, val)"
            />
          </template>
        </el-table-column>

        <el-table-column label="更新时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.updateTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)" :icon="Edit">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)" :icon="Delete">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="totalItems"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑景区对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑景区' : '添加景区'"
      width="600px"
      :top="'3%'"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        class="form-container"
      >
        <el-form-item label="景区名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入景区名称" />
        </el-form-item>

        <!-- <el-form-item label="景区地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入景区地址" />
        </el-form-item> -->

        <el-form-item label="景区分类" prop="category">
          <el-select v-model="form.category" placeholder="请选择景区分类">
            <el-option
              v-for="item in categories"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="门票价格" prop="ticketPrice">
          <el-input-number
            v-model="form.ticketPrice"
            :min="0"
            :precision="2"
            placeholder="请输入门票价格"
          />
          <span style="margin-left: 8px">元</span>
        </el-form-item>

        <!-- <el-form-item label="开放时间" prop="openTime">
          <el-input v-model="form.openTime" placeholder="请输入开放时间，如：08:00-17:30" />
        </el-form-item> -->

        <el-form-item label="景区描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入景区描述"
          />
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入景区联系电话" />
        </el-form-item>

        <el-form-item label="预约须知" prop="reservationNotice">
          <el-input
            v-model="form.reservationNotice"
            type="textarea"
            :rows="3"
            placeholder="请输入预约须知内容"
          />
        </el-form-item>

        <el-form-item label="退款说明" prop="refundPolicy">
          <el-input
            v-model="form.refundPolicy"
            type="textarea"
            :rows="3"
            placeholder="请输入退款说明内容"
          />
        </el-form-item>

        <el-form-item label="使用说明" prop="usageInstructions">
          <el-input
            v-model="form.usageInstructions"
            type="textarea"
            :rows="3"
            placeholder="请输入使用说明内容"
          />
        </el-form-item>

        <el-form-item label="库存数量" prop="stock">
          <el-input-number
            v-model="form.stock"
            :min="0"
            placeholder="请输入库存数量"
          />
          <span style="margin-left: 8px">张</span>
        </el-form-item>

        <el-form-item label="提前预约天数" prop="advanceDays">
          <el-input-number
            v-model="form.advanceDays"
            :min="0"
            placeholder="请输入提前预约天数"
          />
          <span style="margin-left: 8px">天</span>
        </el-form-item>

        <el-form-item label="特色标签">
          <el-select
            v-model="form.features"
            multiple
            placeholder="请选择特色标签"
            style="width: 100%"
          >
            <el-option
              v-for="item in featureOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="推荐等级">
          <el-rate v-model="form.recommendLevel" show-score />
        </el-form-item> -->

        <el-form-item label="景区状态">
          <el-switch
            v-model="form.status"
            :active-value="SCENIC_STATUS.ACTIVE"
            :inactive-value="SCENIC_STATUS.INACTIVE"
          />
        </el-form-item>

        <el-form-item label="封面图片">
          <el-upload
            v-model:file-list="fileList"
            list-type="picture-card"
            :auto-upload="false"
            :multiple="false"
            :limit="1"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            accept="image/jpeg,image/png"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">支持JPG、PNG格式，单张图片不超过2MB，仅支持上传1张封面图片</div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="form-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="submitLoading"
            @click="handleSubmit"
          >
            {{ isEdit ? '更新' : '确认' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, Refresh, Search, Delete, Edit, Picture, Location
} from '@element-plus/icons-vue'
import { scenicApi } from '@/api/scenic'
import { SCENIC_STATUS, RECOMMEND_LEVELS } from '@/utils/constants'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const dialogVisible = ref(false)
const isEdit = ref(false)
const selectedScenics = ref([])
const formRef = ref(null)
const fileList = ref([])

// 景区分类选项
const categories = ref([
  { value: 'historical', label: '历史文化' },
  { value: 'natural', label: '自然风光' },
  { value: 'museum', label: '博物馆' },
  { value: 'park', label: '公园' },
  { value: 'religious', label: '宗教场所' },
  { value: 'entertainment', label: '娱乐休闲' }
])

// 景区特色标签选项
const featureOptions = ref([
  '5A景区', '4A景区', '3A景区',
  '网红打卡', '亲子游', '情侣约会',
  '团队游', '摄影胜地', '文化遗产',
  '自然保护区', '免费开放', '夜景',
  '古建筑', '登山', '赏花'
])

// 筛选表单
const filterForm = reactive({
  status: '',
  category: '',
  minPrice: null,
  maxPrice: null
})

// 表单数据
const form = reactive({
  id: null,
  name: '',
  address: '',
  phone: '',
  category: '',
  ticketPrice: 0,
  openTime: '',
  description: '',
  features: [],
  recommendLevel: 3,
  status: SCENIC_STATUS.ACTIVE,
  images: [],
  // 预约相关字段
  reservationDate: '',
  reservationNotice: '',
  refundPolicy: '',
  usageInstructions: '',
  stock: 100,
  advanceDays: 7
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入景点名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入景点描述', trigger: 'blur' },
    { min: 10, max: 500, message: '描述长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  ticketPrice: [
    { required: true, message: '请输入基础票价', trigger: 'blur' },
    { type: 'number', min: 0, message: '票价不能为负数', trigger: 'blur' }
  ],
  reservationNotice: [
    { required: true, message: '请输入预约须知', trigger: 'blur' },
    { min: 10, max: 1000, message: '预约须知长度在 10 到 1000 个字符', trigger: 'blur' }
  ],
  refundPolicy: [
    { required: true, message: '请输入退款说明', trigger: 'blur' },
    { min: 10, max: 1000, message: '退款说明长度在 10 到 1000 个字符', trigger: 'blur' }
  ],
  usageInstructions: [
    { required: true, message: '请输入使用说明', trigger: 'blur' },
    { min: 10, max: 1000, message: '使用说明长度在 10 到 1000 个字符', trigger: 'blur' }
  ],
  // 以下字段为可选字段，不设置必填验证
  address: [
    { min: 5, max: 200, message: '地址长度在 5 到 200 个字符', trigger: 'blur' }
  ],
  category: [
    { required: false, message: '请选择景区分类', trigger: 'change' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  openTime: [
    { min: 5, max: 50, message: '开放时间长度在 5 到 50 个字符', trigger: 'blur' }
  ],
  stock: [
    { type: 'number', min: 0, message: '库存不能为负数', trigger: 'blur' }
  ],
  advanceDays: [
    { type: 'number', min: 0, message: '提前预约天数不能为负数', trigger: 'blur' }
  ]
}

// 景区数据
const scenicData = ref([])
const totalScenics = ref(0)
// const loading = ref(false)

/**
 * 获取景区列表
 */
const getScenicList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
    
    // 添加搜索条件
    if (searchQuery.value && searchQuery.value.trim()) {
      params.name = searchQuery.value.trim()
    }
    
    // 添加状态筛选
    if (filterForm.status !== '') {
      // 将前端状态值转换为后端枚举值
      const statusMap = {
        [SCENIC_STATUS.ACTIVE]: 0,   // 上架
        [SCENIC_STATUS.INACTIVE]: 1  // 下架
      }
      params.status = statusMap[filterForm.status]
    }
    
    console.log('发送景区查询请求，参数:', params)
    const data = await scenicApi.getPage(params)
    console.log('接收到的景区数据:', data)
    
    // 处理返回的数据结构
    scenicData.value = data.records || []
    totalScenics.value = data.total || (data.pages * pageSize.value) || 0
    currentPage.value = data.pageNum || 1
    
    // 处理景区数据，添加前端需要的字段
    scenicData.value = await Promise.all(scenicData.value.map(async (scenic) => {
      // 获取真实库存数据
      let realStock = 100 // 默认库存
      try {
        // 假设景点ID等于预约ID，如果不是请调整这里的逻辑
        const orderDetails = await scenicApi.getScenicOrderDetails(scenic.id)
        realStock = orderDetails.totalAmount || 100
        console.log(`景点 ${scenic.name} (ID: ${scenic.id}) 的库存: ${realStock}`)
      } catch (error) {
        console.warn(`获取景点 ${scenic.name} (ID: ${scenic.id}) 库存失败:`, error.message)
        // 如果获取失败，使用默认值
        realStock = 100
      }

      return {
        ...scenic,
        // 状态转换：后端数字 -> 前端常量
        status: scenic.status === 1 ? SCENIC_STATUS.ACTIVE : SCENIC_STATUS.INACTIVE,
        // 处理封面图片URL
        coverImage: scenic.coverImage ? 
          (scenic.coverImage.startsWith('http') ? 
            scenic.coverImage : 
            `http://192.168.199.178:9000/fznostalgia/scenic/${scenic.coverImage}`
          ) : 'https://via.placeholder.com/300x200?text=暂无图片',
        // 添加默认字段
        category: scenic.category || 'other',
        ticketPrice: scenic.basePrice || 0,
        openTime: scenic.openTime || '09:00-17:00',
        features: scenic.features || [],
        recommendLevel: scenic.rating || 4.0,
        images: scenic.images || [],
        // 预约相关字段
        phone: scenic.phone || '',
        reservationNotice: scenic.bookingNotice || '',
        refundPolicy: scenic.refundPolicy || '',
        usageInstructions: scenic.usageGuide || '',
        stock: realStock, // 使用真实库存数据
        advanceDays: scenic.advanceDays || 7
      }
    }))
    
    console.log('处理后的景区数据:', scenicData.value)
  } catch (error) {
    console.error('获取景区列表失败:', error)
    ElMessage.error(error.message || '获取景区列表失败')
  } finally {
    loading.value = false
  }
}

// 计算属性 - 景区列表（直接使用 API 返回的数据）
const scenicList = computed(() => {
  return scenicData.value
})

// 计算属性 - 开放中的景区数量
const activeScenics = computed(() => 
  scenicData.value.filter(scenic => scenic.status === SCENIC_STATUS.ACTIVE).length
)

// 计算属性 - 总页数
const totalItems = computed(() => totalScenics.value)

// 方法
const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

const getCategoryName = (categoryValue) => {
  const category = categories.value.find(item => item.value === categoryValue)
  return category ? category.label : categoryValue
}

const handleSearch = () => {
  currentPage.value = 1
  getScenicList()
}

const handleFilter = () => {
  currentPage.value = 1
  getScenicList()
}

const handleResetFilter = () => {
  filterForm.status = ''
  filterForm.category = ''
  filterForm.minPrice = null
  filterForm.maxPrice = null
  searchQuery.value = ''
  currentPage.value = 1
  getScenicList()
  ElMessage.success('筛选条件已重置')
}

const handleRefresh = () => {
  getScenicList()
  ElMessage.success('数据已刷新')
}

const handleSelectionChange = (selection) => {
  selectedScenics.value = selection
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getScenicList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getScenicList()
}

const handleAddScenic = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  resetForm()
  
  // 填充表单数据
  Object.keys(form).forEach(key => {
    if (key in row) {
      form[key] = row[key]
    }
  })
  
  // 处理封面图片（只处理一张封面图片）
  if (row.coverImage) {
    fileList.value = [{
      name: 'cover-image',
      url: row.coverImage
    }]
  } else {
    fileList.value = []
  }
  
  console.log('编辑景点数据:', row)
  console.log('设置的文件列表:', fileList.value)
  
  dialogVisible.value = true
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  
  Object.assign(form, {
    id: null,
    name: '',
    address: '',
    category: '',
    ticketPrice: 0,
    openTime: '',
    description: '',
    features: [],
    recommendLevel: 3,
    status: SCENIC_STATUS.ACTIVE,
    images: []
  })
  
  fileList.value = []
}

const handleFileChange = (file, uploadFileList) => {
  console.log('文件上传变化:', file, uploadFileList)
  
  // 限制上传数量为1张
  if (uploadFileList.length > 1) {
    uploadFileList.splice(0, uploadFileList.length - 1)
    ElMessage.warning('只能上传1张封面图片')
  }
  
  // 检查文件类型和大小
  const isImage = file.raw && (file.raw.type === 'image/jpeg' || file.raw.type === 'image/png')
  const isLt2M = file.raw && (file.raw.size / 1024 / 1024 < 2)
  
  if (!isImage) {
    ElMessage.error('只能上传JPG或PNG格式的图片')
    const index = uploadFileList.indexOf(file)
    if (index > -1) {
      uploadFileList.splice(index, 1)
    }
    return
  }
  
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB')
    const index = uploadFileList.indexOf(file)
    if (index > -1) {
      uploadFileList.splice(index, 1)
    }
    return
  }
  
  // 更新文件列表
  fileList.value = uploadFileList
  console.log('更新后的文件列表:', fileList.value)
}

const handleFileRemove = (file, uploadFileList) => {
  console.log('移除文件:', file, uploadFileList)
  // 更新文件列表
  fileList.value = uploadFileList
  console.log('移除后的文件列表:', fileList.value)
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    if (isEdit.value) {
      // 更新现有景点 - 调用真实接口
      console.log('开始更新景点，表单数据:', form)
      
      // 准备景点数据，映射到后端DTO字段
      const scenicSpotData = {
        id: form.id, // 必须包含ID用于更新
        name: form.name,
        description: form.description,
        basePrice: Math.round(form.ticketPrice * 100), // 转换为分
        bookingNotice: form.reservationNotice,
        refundPolicy: form.refundPolicy,
        usageGuide: form.usageInstructions,
        status: form.status === SCENIC_STATUS.ACTIVE ? 1 : 0 // 转换状态值
      }
      
      console.log('准备发送的更新景点数据:', scenicSpotData)
      
      // 获取封面图片文件（只有当用户上传了新图片时才传递）
      let coverImageFile = null
      if (fileList.value.length > 0 && fileList.value[0].raw) {
        // 如果有新上传的图片文件
        coverImageFile = fileList.value[0].raw
        console.log('新上传的封面图片文件:', coverImageFile)
      }
      
      // 调用真实的更新接口
      const result = await scenicApi.updateById(scenicSpotData, coverImageFile)
      console.log('更新景点成功，返回结果:', result)
      
      ElMessage.success(result.msg || '景点更新成功')
      
      // 刷新景区列表
      await getScenicList()
    } else {
      // 添加新景区 - 调用真实接口
      console.log('开始添加景点，表单数据:', form)
      
      // 准备景点数据，映射到后端DTO字段
      const scenicSpotData = {
        name: form.name,
        description: form.description,
        basePrice: Math.round(form.ticketPrice * 100), // 转换为分
        bookingNotice: form.reservationNotice,
        refundPolicy: form.refundPolicy,
        usageGuide: form.usageInstructions,
        status: form.status === SCENIC_STATUS.ACTIVE ? 1 : 0 // 转换状态值
      }
      
      console.log('准备发送的景点数据:', scenicSpotData)
      
      // 获取封面图片文件
      let coverImageFile = null
      if (fileList.value.length > 0 && fileList.value[0].raw) {
        coverImageFile = fileList.value[0].raw
        console.log('封面图片文件:', coverImageFile)
      }
      
      // 调用真实的添加接口
      const result = await scenicApi.insert(scenicSpotData, coverImageFile)
      console.log('添加景点成功，返回结果:', result)
      
      ElMessage.success(result.msg || '景点添加成功')
      
      // 刷新景区列表
      await getScenicList()
    }
    
    dialogVisible.value = false
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(error.message || '操作失败')
  } finally {
    submitLoading.value = false
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除景点 "${row.name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    console.log('开始删除景点，ID:', row.id)
    loading.value = true
    
    // 调用真实的删除接口
    const result = await scenicApi.deleteById(row.id)
    console.log('删除景点成功，返回结果:', result)
    
    ElMessage.success(result.msg || '景点删除成功')
    
    // 刷新景区列表
    await getScenicList()
    
  } catch (error) {
    if (error.message && error.message !== '已取消删除') {
      console.error('删除景点失败:', error)
      ElMessage.error(error.message || '删除景点失败')
    } else {
      ElMessage.info('已取消删除')
    }
  } finally {
    loading.value = false
  }
}

const handleBatchDelete = async () => {
  if (selectedScenics.value.length === 0) {
    ElMessage.warning('请先选择要删除的景区')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedScenics.value.length} 个景区吗？此操作不可恢复。`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟API调用
    loading.value = true
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 批量删除
    const ids = selectedScenics.value.map(item => item.id)
    scenicData.value = scenicData.value.filter(item => !ids.includes(item.id))
    
    ElMessage.success(`成功删除 ${ids.length} 个景区`)
    selectedScenics.value = []
  } catch (error) {
    ElMessage.info('已取消删除')
  } finally {
    loading.value = false
  }
}

const handleStatusChange = async (row, status) => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 更新状态
    row.status = status
    row.updateTime = new Date().toLocaleString('zh-CN')
    
    const statusText = status === SCENIC_STATUS.ACTIVE ? '开放' : '关闭'
    ElMessage.success(`景区 "${row.name}" 已${statusText}`)
  } catch (error) {
    // 恢复原状态
    row.status = row.status === SCENIC_STATUS.ACTIVE ? SCENIC_STATUS.INACTIVE : SCENIC_STATUS.ACTIVE
    ElMessage.error('状态更新失败')
  }
}

// 生命周期钩子
onMounted(() => {
  // 初始化加载景区数据
  getScenicList()
})
</script>

<style scoped>
.scenic-management {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.header-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 10px;
}

.header-stats {
  display: flex;
  margin-bottom: 15px;
}

.stat-item {
  margin-right: 30px;
  font-size: 14px;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #409EFF;
  margin-right: 5px;
}

.filter-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.filter-item {
  margin-right: 15px;
  margin-bottom: 10px;
}

/* 新增列的样式 */
.description-text,
.notice-text,
.policy-text,
.guide-text {
  font-size: 13px;
  line-height: 1.4;
  color: #606266;
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.description-text {
  color: #303133;
}

.notice-text {
  color: #E6A23C;
}

.policy-text {
  color: #F56C6C;
}

.guide-text {
  color: #67C23A;
}

.action-bar {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
}

.table-container {
  margin-bottom: 20px;
}

.scenic-name {
  font-weight: bold;
  font-size: 16px;
}

.scenic-address {
  font-size: 12px;
  color: #606266;
  display: flex;
  align-items: center;
}

.scenic-name {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 5px;
}

.scenic-address {
  font-size: 12px;
  color: #606266;
  display: flex;
  align-items: center;
}

.address-icon {
  margin-right: 4px;
  font-size: 12px;
}

.feature-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.low-stock {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}

.form-container {
  max-width: 600px;
}

.upload-container {
  margin-bottom: 20px;
}

.upload-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 5px;
}

.form-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.form-footer .el-button {
  margin-left: 10px;
}

.recommend-level {
  display: flex;
  align-items: center;
}

.recommend-level-text {
  margin-left: 10px;
  font-size: 14px;
  color: #606266;
}
</style>